<template>
  <div>
    <el-dialog :title="title" :visible.sync="visible" width="60%" append-to-body custom-class="import-dialog">
      <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" @submit.native.prevent>
          <el-form-item label="小区" prop="estateName">
            <el-input v-model="queryParams.estateName" placeholder="请输入小区" clearable style="width: 240px"
                      @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="楼栋" prop="buildingName">
            <el-input v-model="queryParams.buildingName" placeholder="请输入楼栋" clearable style="width: 240px"
                      @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="房间" prop="roomNumber">
            <el-input v-model="queryParams.roomNumber" placeholder="请输入房间" clearable style="width: 240px"
                      @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table :row-key="getRowKey" v-loading="loading" :data="list" @select="handleSelectChange"
                  @select-all="handleSelectAllChange" ref="table">
          <!-- <el-table-column label="房间编号" align="center" prop="houseId" /> -->
          <el-table-column align="center" prop="houseCode" type="selection" v-if="isMultiple && selectable"/>
          <el-table-column label="楼盘" align="center" prop="estateName"/>
          <el-table-column label="楼栋" align="center" prop="buildingName"/>
          <el-table-column label="单元" align="center" prop="unitName"/>
          <el-table-column label="房间" align="center" prop="roomNumber"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="!isMultiple && selectable">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleSubmit(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"/>
      </div>
      <div slot="footer" class="dialog-footer" v-show="isMultiple && selectable">
        <el-button type="primary" size="small" @click="handleSubmit">确定</el-button>
        <el-button size="small" @click="close">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listRoom,listRoomByAllocation} from "@/api/house/room";

export default {
  props: {
    selectable: {
      type: Boolean,
      default: true,
    },
    title: {
      default: "选择房间",
    },
    show: {
      default: false,
    },
    isMultiple: {
      type: Boolean,
      default: false,
    },
    data:{},
    // 已选列表
    seletedList: {
      type: Array,
      default: () => [],
    },
    // api类型
    apiType: {
      type: String,
      default: "listRoom"
    },
    // api参数
    apiParams: {}
  },
  dicts: [],
  data() {
    return {
      // api类型映射
      apiTypeMap: {
        "listRoom": listRoom, // 房间列表
        "listRoomByAllocation": listRoomByAllocation // 查询已配置的房屋信息
      },

      // 当前已选列表
      currentSelectList: [],
      // 已选房间Ids
      currentSelectIds: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        estateName: undefined,
        buildingName: undefined,
        roomNumber: undefined,
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      //列表
      list: [],
    };
  },
  computed: {
    visible: {
      get() {
        return this.show;
      },
      set(val) {
        this.$emit("update:show", val);
      }
    },

  },
  watch: {
    visible(val) {
      if (val) {
        this.init();
      }
    },
  },
  methods: {
    init() {
      this.reset()
      this.getList();
    },
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        estateName: undefined,
        buildingName: undefined,
        roomNumber: undefined,
        ...this.apiParams
      }
      this.resetForm("queryForm");
      this.currentSelectList = [...this.seletedList]
      this.currentSelectIds = this.currentSelectList.map(item => item.houseId)

    },
    handleQuery() {
      this.getList();
    },
    resetQuery() {
      // this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查询房间列表 */
    getList() {
      this.loading = true;
      this.apiTypeMap[this.apiType](this.queryParams).then((response) => {
        if(this.apiType === "listRoomByAllocation"){
          this.list = response.rows.map(item => item.house);
        }else{
          this.list = response.rows;
        }
        this.total = response.total;
        this.loading = false;

        // 勾选已选房间
        this.$nextTick(() => {
          if (this.isMultiple) {
            let selectedList = this.list.filter(item => this.currentSelectIds.includes(item.houseId))
            selectedList.forEach(item => {
              this.$refs.table.toggleRowSelection(item, true)
            })
          }
        });
      });
    },
    // 获取行key
    getRowKey(row) {
      return row.houseId;
    },
    // 全选框选中/取消
    handleSelectAllChange(selection) {
      if (selection.length) {
        selection.filter(item => !this.currentSelectIds.includes(item.houseId)).forEach(item => {
          this.handleSelectChange(selection, item)
        })
      } else {
        this.list.forEach(item => {
          this.handleSelectChange(selection, item)
        })
      }

    },
    //单选框选中
    handleSelectChange(selection, row) {
      let index = this.currentSelectList.findIndex(item => item.houseId === row.houseId)
      if (index === -1) {
        this.currentSelectList.push(row)
        this.currentSelectIds.push(row.houseId)
      } else {
        this.currentSelectList.splice(index, 1)
        this.currentSelectIds.splice(index, 1)
      }
    },
    /** 提交选择房间 */
    handleSubmit(item) {
      if (this.isMultiple) {
        this.$emit("success", [...this.currentSelectList]);
      } else {
        this.$emit("success", [item]);
      }
      this.close();
    },
    close() {
      this.reset()
      this.visible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/styles/dialog.scss";

.dialog-footer {
  text-align: center;
}
</style>
